<?php
/**
 * Created by PhpStorm.
 * User: lenvo
 * Date: 2018/6/24
 * Time: 19:57
 */

namespace app\merchant\service;


use app\common\service\Service;
use think\Db;
use think\Loader;

class Mermenu extends Service
{
    protected $mermenu_model = null;
    public function __construct(){
        parent::__construct();
        $this->mermenu_model = Loader::model('mer_menu');
    }

    public function get_auth_menu($mer_id, $rule_value){
        $current = get_top_menu($rule_value,1);//level = 1的菜单
        $menus = $this->mermenu_model->get_auth_menu($mer_id);
        if($menus) {
            $tree = $this->build_tree($menus,$current['id'],$rule_value);
            return $this->ret->setCode(\app\merchant\define\Merchant::$Code_Mer_Success)
                ->setData("tree",$tree);
        }else {
            return $this->ret->setCode(\app\merchant\define\Merchant::$Code_Mer_Error)
                ->setMsg("获取菜单列表失败");
        }
    }

    public function get_auth_button($mer_id, $rule_value) {
        $buttons = $this->mermenu_model->get_auth_button($mer_id,$rule_value);
        $ret = [];
        foreach ($buttons as $_){
            array_push($ret,$_['rule_value']);
        }
        return $this->ret->setCode(\app\merchant\define\Merchant::$Code_Mer_Success)
            ->setData("buttons",$ret);

    }

    private function build_tree($list,$id1,$rule2) {
        $top_menus = $this->filter($list,"pid",0);
        foreach($top_menus as $key => $_) {
            $top_menus[$key]['childs'] = $this->filter($list,"pid",$_['id']);
            if($_['id'] == $id1) {
                $top_menus[$key]['selected'] = true;
                foreach($top_menus[$key]['childs'] as $k => $__) {
                    if($__['rule_value'] == $rule2) {
                        $top_menus[$key]['childs'][$k]['selected'] = true;
                    }else {
                        $top_menus[$key]['childs'][$k]['selected'] = false;
                    }
                }
            }else {
                $top_menus[$key]['selected'] = false;
            }
            if($_['action'] == 'default') {
                if(count($top_menus[$key]['childs']) > 0) {
                    $top_menus[$key]['url'] = url($top_menus[$key]['childs'][0]['rule_value']);
                }else {
                    $top_menus[$key]['url'] = url("{$_['model']}/{$_['controller']}/index");
                }
            }else {
                $top_menus[$key]['url'] = url($_['rule_value']);
            }
        }
        return $top_menus;
    }
    private function filter($list,$condition,$value) {
        $ret = [];
        foreach($list as $key => $_) {
            $_ = $_->toArray();
            if($_[$condition] == $value) {
                array_push($ret , $_);
                //unset($list[$key]);
            }
        }
        //dump($list);
        return $ret;
    }
}